<?php
/**
 * WP-Click-Tracker Admin Module
 *
 * Contains all the click tracker functions for the administration module.
 *
 * @author Eric Lamb <eric@ericlamb.net>
 * @package    wp-click-tracker
 * @version 0.4.1
 * @filesource
 * @copyright 2009 Eric Lamb.
 */

function wp_click_track_validate_mod_link($data){

	$errors = array();
	if(!isset($data['link_name']) || $data['link_name'] == ''){
		$errors['link_name'] = TRUE;
	}

	if(!isset($data['link_destination']) || $data['link_destination'] == ''){
		$errors['link_destination'] = TRUE;
	}

	return $errors;

}

function wp_click_track_mod_link_form($link_id = FALSE, $req = 'add'){
	global $wpdb;
	
	$page = $_REQUEST['page'];
	$errors = FALSE;
	if($link_id){
		$link_data = wp_click_track_get_link_data(" WHERE link_id = '$link_id'");
		$submit_value = "Edit Link";
		$def_name = (isset($_POST['link_name']) ? $_POST['link_name'] : $link_data['0']->link_title);
		$def_desc = (isset($_POST['description']) ? $_POST['description'] : $link_data['0']->link_desc);
		$def_dest = (isset($_POST['link_destination']) ? $_POST['link_destination'] : $link_data['0']->link_destination);

	} else {
		$submit_value = "Add Link";
		$def_name = (isset($_POST['link_name']) ? $_POST['link_name'] : FALSE);
		$def_desc = (isset($_POST['description']) ? $_POST['description'] : FALSE);
		$def_dest = (isset($_POST['link_destination']) ? $_POST['link_destination'] : FALSE);
	}

	if(isset($_POST['link_name'])){
		$errors = wp_click_track_validate_mod_link($_POST);
		if(count($errors) == '0'){
			$errors = FALSE;
		} else {
			echo '<div class="error">'.__('Please fill out all required fields.').'</div>';
		}
	}

?>

	<form name="add_click_track" id="add_click_track" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
	<?php
		if($link_id){
			echo '<input type="hidden" name="link" value="'.$link_id.'">';
		}
	?>
	<input type="hidden" name="req" value="<?php echo $req; ?>" />
	<input type="hidden" name="page" value="<?php echo $page; ?>" />
	<input type="hidden" name="mod_wpct_link" value="yes" />

	<?php
	if(isset($errors['link_name'])){
		echo '<br /><br /><div class="error">'.__('Required').'</div>';
	}
	?>
	<table class="widefat comments-box " cellspacing="0">
	<thead>
		<tr>
			<th><label for="link_name">Link Name (required)</label></th>
		</tr>
		<tr>
			<td><div class="form-field"><input name="link_name" id="link_name" type="text" value="<?php echo $def_name; ?>" size="40"/></div> Example: Download WP-Click-Tracker</td>
		</tr>
	<tbody id="the-comment-list" class="list:comment">
	</tbody>
	</table>

	<br />
	<?php
	if(isset($errors['link_destination'])){
		echo '<div class="error">'.__('Required').'</div>';
	}
	?>
	<table class="widefat comments-box " cellspacing="0">
	<thead>
		<tr>
			<th><label for="link_destination">Link Destination (required)</label></th>
		</tr>
		<tr>
			<td><div class="form-field"><input name="link_destination" id="link_destination" type="text" value="<?php echo $def_dest; ?>" size="40" /></div> Example: <code>http://<?php echo $_SERVER['HTTP_HOST']; ?>/</code> &#8212; don&#8217;t forget the <code>http://</code></td>
		</tr>
	<tbody id="the-comment-list" class="list:comment">
	</tbody>
	</table>

	<br />

	<table class="widefat comments-box " cellspacing="0">
	<thead>
		<tr>
			<th><label for="description">Description (optional)</label></th>
		</tr>
		<tr>
			<td><div class="form-field"><textarea name="description" id="description" rows="5" cols="40"><?php echo $def_desc; ?></textarea></div> This will be shown when someone hovers over the link.</td>
		</tr>
	<tbody id="the-comment-list" class="list:comment">
	</tbody>
	</table>

	<p class="submit"><input type="submit" class="button" name="submit" value="<?php echo $submit_value; ?>" /></p>
	</form>
<?
}


/**
 * Displays the pie chart for the hour clicks
 *
 * @param   aray  $result	array() of clicks
 * @return  void
 */
function wp_click_track_display_pie_hour_chart($result){

	if(!isset($result) || !$result){
		return FALSE;
	}
	$total = count($result);
	$js = '';
	for($i=0;$i<$total;$i++){
		$Hour = ($result[$i]->Hour > 12 ? ($result[$i]->Hour-12).' PM' : $result[$i]->Hour.' AM');
		if($Hour == '12 AM'){ $Hour = '12 PM'; }
		if($Hour == '0 AM'){ $Hour = '12 AM'; }
		$js .= "data.setValue($i, 0, '$Hour');\ndata.setValue($i, 1, ".$result[$i]->Clicks.");\n";
	}
?>

	<script type="text/javascript">
	  google.load("visualization", "1", {packages:["piechart"]});
	  google.setOnLoadCallback(drawChart);
	  function drawChart() {
		var data = new google.visualization.DataTable();
		data.addColumn('string', 'Hour');
		data.addColumn('number', 'Clicks');
		data.addRows(<?php echo $total; ?>);
		<?php echo $js; ?>

		var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
		chart.draw(data, {width: 500, height: 400, is3D: true, title: 'Clicks By Hour', backgroundColor: '#f9f9f9', legend: 'top', legendBackgroundColor: '#f1f1f1'});
	  }
	</script>
	<div id="chart_div"></div>
	<?
}
 
/**
 * Displays the pie chart for the day clicks
 *
 * @param   aray  $result	array() of clicks
 * @return  void
 */
function wp_click_track_display_pie_day_chart($result){

	if(!isset($result) || !$result){
		return FALSE;
	}

	$js = '';
	$total = count($result);
	for($i=0;$i<$total;$i++){
		$Day = wp_click_track_date_by_num($i);
		$js .= "data.setValue($i, 0, '$Day');\ndata.setValue($i, 1, ".$result[$i].");\n";
	}
?>

	<script type="text/javascript">
	  google.load("visualization", "1", {packages:["piechart"]});
	  google.setOnLoadCallback(drawChart);
	  function drawChart() {
		var data = new google.visualization.DataTable();
		data.addColumn('string', 'Day');
		data.addColumn('number', 'Clicks');
		data.addRows(<?php echo $total; ?>);
		<?php echo $js; ?>

		var chart = new google.visualization.PieChart(document.getElementById('day_chart_div'));
		chart.draw(data, {width: 500, height: 400, is3D: true, title: 'Clicks By Day', backgroundColor: '#f9f9f9', legend: 'top', legendBackgroundColor: '#f1f1f1'});
	  }
	</script>
	<div id="day_chart_div"></div>
	<?
}

/**
 * Displays the message on admin page
 *
 * @return  void
 */
function wp_click_track_admin_message($message){
?>
<div class="updated">
	<strong><p><?php echo $message; ?></p></strong>
</div>
<?
}

/**
 * Returns the day of week from a MySQL date number
 *
 * @param   aray  $result	array() of clicks
 * @return  string
 */
function wp_click_track_date_by_num($num){
	
	switch($num){
		case '0':
			return 'Monday';
		break;
		case '1':
			return 'Tuesday';
		break;
		case '2':
			return 'Wednesday';
		break;
		case '3':
			return 'Thursday';
		break;
		case '4':
			return 'Friday';
		break;
		case '5':
			return 'Saturday';
		break;
		case '6':
			return 'Sunday';
		break;
	}
}
/**
 * Lists all the links for a situation
 *
 * @return  void
 */
function wp_click_track_list_links($result, $total, $date_ranges = FALSE, $display_message = TRUE){
?>
<table class="widefat comments-box " cellspacing="0">
<thead>
	<tr>
    <th>Title</th>
	<th>Destination</th>
    <th nowrap>Total Clicks</th>
	<th nowrap>Unique Clicks</th>
	<?
	if($date_ranges){
	?>
    <th nowrap>First Click</th>
	<th nowrap>Last Click</th>
	<? } ?>
</thead>
<?

	for($i=0;$i<$total;$i++){
?>
  </tr>
	<tr>
    <td><a href="<?=$_SERVER['PHP_SELF'];?>?page=<?=$_REQUEST['page'];?>&link=<?=$result[$i]->link_id; ?>"><?php echo $result[$i]->link_title;?></a></td>
    <td><a href="<?php echo $result[$i]->link_destination;?>" target="_blank" title="<?php echo $result[$i]->link_title;?>">
	<?=(strlen($result[$i]->link_destination) >= 50 ? substr($result[$i]->link_destination,0,50).'...' : $result[$i]->link_destination);?></a></td>
    <td><?php echo number_format_i18n($result[$i]->link_total_clicks);?></td>
    <td><?php echo number_format_i18n($result[$i]->link_unique_clicks);?></td>
	<?
	if($date_ranges){
	?>
    <td nowrap><?php echo $date_ranges['first_click'];?></td>
    <td nowrap><?php echo $date_ranges['last_click'];?></td>
	<? } ?>
  </tr>
<?
	}
?>

<tbody id="the-comment-list" class="list:comment">
</tbody>
</table>
<?
	if($display_message){
?>
NOTE: Only links that have been clicked are above.
<? 
	} 
}

/**
 * Adds the javascript embed to the admin header
 *
 * @return  void
 */
function wp_click_tracker_admin_head(){

	if(substr($_SERVER['PHP_SELF'],-18) == 'wp-admin/index.php' || isset($_REQUEST['page']) && $_REQUEST['page'] == 'wp-click-track/click-tracker.php'){
		echo '<script type="text/javascript" src="http://www.google.com/jsapi"></script>';
	}
}

function wp_click_track_admin_list_ip_page($ip_addr, $link_id, $req, $page, $paged, $ref_paged){
	global $wpdb, $click_tracker_dist_get;

	//base url for the admin page (build new links on top of)
	$page_url = $_SERVER['PHP_SELF'].'?page='.$page.'&link='.$link_id.'&ip='.$ip_addr;

	echo '<table width="100%"><tr><td><a name="in_refer"></a><h3>Click Path for '.$ip_addr.'</h3></td><td>';

	$sql = "SELECT * FROM ".$wpdb->prefix."tracking_clicks tc,".$wpdb->prefix."tracking_links tl WHERE tc.click_ip = '$ip_addr' and tc.link_id = tl.link_id ORDER BY click_date DESC";
	$result = $wpdb->get_results($sql);
	$total_refer = count($result);
	unset($result);

	$plugin_options = get_option('click_tracker');
	$link_page_total = $plugin_options['referrer_count'];

	$limitvalue = $ref_paged * $link_page_total - ($link_page_total);
	$numofpages = ceil($total_refer / $link_page_total);

	$sql = "SELECT * FROM ".$wpdb->prefix."tracking_clicks tc,".$wpdb->prefix."tracking_links tl WHERE tc.click_ip = '$ip_addr' and tc.link_id = tl.link_id ORDER BY click_date DESC LIMIT $limitvalue,$link_page_total"; 
	$referr_data = $wpdb->get_results($sql);
	$count = count($referr_data);

	$page_links = paginate_links( array(
		'base' => add_query_arg( 'ref_paged', '%#%#in_refer' ),
		'format' => '',
		'prev_text' => __('&laquo;'),
		'next_text' => __('&raquo;'),
		'total' => $numofpages,
		'current' => $ref_paged
	));

	if ( $page_links ) { 
		$page_links_text = sprintf( '<span class="displaying-num">' . __( 'Displaying %s&#8211;%s of %s' ) . '</span>%s',
		number_format_i18n( ( $ref_paged - 1 ) * $link_page_total + 1 ),
		number_format_i18n( min( $ref_paged * $link_page_total, $total_refer ) ),
		number_format_i18n( $total_refer ),
		$page_links
	); 
		echo "<div class='tablenav'><div class='tablenav-pages'>$page_links_text</div></div>";
	}
	?>
	</td></tr></table>

	<table class="widefat comments-box " cellspacing="0">
	<thead>
		<tr>
		<th>Link</th>
		<th>Referrer</th>
		<th>Date</th>
<?
	if($count >= '1'){
		for($i=0;$i<$count;$i++){
	?>
	  </tr>
		<tr>
		<td><a href=""><?=$referr_data[$i]->link_title;?></a></td>
		<td><a href="<?php echo $referr_data[$i]->click_refer;?>" target="_blank" title=""><?=(strlen($referr_data[$i]->click_refer) >= 100 ? substr($referr_data[$i]->click_refer,0,100).'...' : $referr_data[$i]->click_refer);?></a></a></td>
		<td><?=mysql2date(get_option('date_format').' '.get_option('time_format'),$referr_data[$i]->click_date);?></td>
	<?
		}
	} else {
		echo '</tr><tr><td colspan="3">No Referrers Found</td></tr>';
	}
?>
	<tbody id="the-comment-list" class="list:comment">
	</tbody>
	</table>

	<?php
	if ( $page_links ) { 
		$page_links_text = sprintf( '<span class="displaying-num">' . __( 'Displaying %s&#8211;%s of %s' ) . '</span>%s',
		number_format_i18n( ( $ref_paged - 1 ) * $link_page_total + 1 ),
		number_format_i18n( min( $ref_paged * $link_page_total, $total_refer ) ),
		number_format_i18n( $total_refer ),
		$page_links
	); 
		echo "<div class='tablenav'><div class='tablenav-pages'>$page_links_text</div></div>";
	}

}

function wp_click_track_admin_list_link_page($link_id, $req, $page, $paged, $ref_paged) {
	global $wpdb, $click_tracker_dist_get;

	//base url for the admin page (build new links on top of)
	$page_url = $_SERVER['PHP_SELF'].'?page='.$page.'&link='.$link_id;

	$BuildWhere = " WHERE link_id = '".$wpdb->escape($link_id)."' LIMIT 1";
	$result = wp_click_track_get_link_data($BuildWhere);

	//get the first and last click dates
	$sql = "SELECT MIN(click_date) as first_date,MAX(click_date) as last_date FROM ".$wpdb->prefix."tracking_clicks WHERE link_id='".$wpdb->escape($link_id)."' LIMIT 1";
	$click_dates = $wpdb->get_results($sql);

	$date_ranges['first_click'] = ($click_dates['0']->first_date == '' ? 'N/A' : mysql2date(get_option('date_format').' '.get_option('time_format'),$click_dates['0']->first_date));
	$date_ranges['last_click'] = ($click_dates['0']->last_date == '' ? 'N/A' : mysql2date(get_option('date_format').' '.get_option('time_format'),$click_dates['0']->last_date));

	$total = count($result);

	$site_url = get_option( 'siteurl' );
	$dist_link = $site_url.'?'.$click_tracker_dist_get.'='.$link_id;

	?>

	<h3>Distributable Link</h3>
	<table class="widefat comments-box " cellspacing="0">
	<thead>
		<tr>
			<th width="50%">Embed Code</th>
			<th width="50%">URL</th>
		</tr>
		<tr>
			<td><code> &lt;a href="<?php echo $dist_link; ?>"&gt;<?php echo $result['0']->link_title; ?>&lt;/a&gt;</code></td>
			<td><?php echo $dist_link; ?></td>
		</tr>

	<tbody id="the-comment-list" class="list:comment">
	</tbody>
	</table>
	<?
	echo '<h3>Link Data</h3>';
	wp_click_track_list_links($result, $total, $date_ranges, FALSE);

	echo '<table width="100%"><tr><td><a name="in_refer"></a><h3>Top Referrers</h3></td><td>';

	$sql = "SELECT COUNT(click_refer) AS REFERCNT FROM ".$wpdb->prefix."tracking_clicks WHERE link_id = '".$wpdb->escape($link_id)."' AND click_refer != '' GROUP BY click_refer ORDER BY REFERCNT DESC ";
	$result = $wpdb->get_results($sql);
	$total_refer = count($result);
	unset($result);

	$plugin_options = get_option('click_tracker');
	$link_page_total = $plugin_options['referrer_count'];

	$limitvalue = $ref_paged * $link_page_total - ($link_page_total);
	$numofpages = ceil($total_refer / $link_page_total);

	$sql = "SELECT COUNT(click_refer) AS REFERCNT, click_refer FROM ".$wpdb->prefix."tracking_clicks WHERE link_id = '".$wpdb->escape($link_id)."' AND click_refer != '' GROUP BY click_refer ORDER BY REFERCNT DESC LIMIT $limitvalue,$link_page_total"; 
	$referr_data = $wpdb->get_results($sql);
	$count = count($referr_data);

	$page_links = paginate_links( array(
		'base' => add_query_arg( 'ref_paged', '%#%#in_refer' ),
		'format' => '',
		'prev_text' => __('&laquo;'),
		'next_text' => __('&raquo;'),
		'total' => $numofpages,
		'current' => $ref_paged
	));

	if ( $page_links ) { 
		$page_links_text = sprintf( '<span class="displaying-num">' . __( 'Displaying %s&#8211;%s of %s' ) . '</span>%s',
		number_format_i18n( ( $ref_paged - 1 ) * $link_page_total + 1 ),
		number_format_i18n( min( $ref_paged * $link_page_total, $total_refer ) ),
		number_format_i18n( $total_refer ),
		$page_links
	); 
		echo "<div class='tablenav'><div class='tablenav-pages'>$page_links_text</div></div>";
	}
	?>
	</td></tr></table>

	<table class="widefat comments-box " cellspacing="0">
	<thead>
		<tr>
		<th>Count</th>
		<th>Referrer</th>
<?
	if($count >= '1'){
		for($i=0;$i<$count;$i++){
	?>
	  </tr>
		<tr>
		<td><?=$referr_data[$i]->REFERCNT;?></td>
		<td><a href="<?php echo $referr_data[$i]->click_refer;?>" target="_blank" title=""><?=(strlen($referr_data[$i]->click_refer) >= 125 ? substr($referr_data[$i]->click_refer,0,125).'...' : $referr_data[$i]->click_refer);?></a></a></td>
	<?
		}
	} else {
		echo '</tr><tr><td colspan="2">No Referrers Found</td></tr>';
	}
?>
	<tbody id="the-comment-list" class="list:comment">
	</tbody>
	</table>

	<?php
	if ( $page_links ) { 
		$page_links_text = sprintf( '<span class="displaying-num">' . __( 'Displaying %s&#8211;%s of %s' ) . '</span>%s',
		number_format_i18n( ( $ref_paged - 1 ) * $link_page_total + 1 ),
		number_format_i18n( min( $ref_paged * $link_page_total, $total_refer ) ),
		number_format_i18n( $total_refer ),
		$page_links
	); 
		echo "<div class='tablenav'><div class='tablenav-pages'>$page_links_text</div></div>";
	}
	?>

	<table width="100%"><tr><td>
	<?php
	echo '<a name="in_clicks"></a><h3>Individual Clicks</h3>';

	echo '</td><td align="right">';

	$sql = "SELECT COUNT(click_ip) AS CLICKCNT FROM ".$wpdb->prefix."tracking_clicks WHERE link_id = '".$wpdb->escape($link_id)."' GROUP BY click_ip";
	$result = $wpdb->get_results($sql);
	$total_clicks = count($result);
	unset($result);

	$plugin_options = get_option('click_tracker');
	$link_page_total = $plugin_options['click_count'];

	$limitvalue = $paged * $link_page_total - ($link_page_total);
	$numofpages = ceil($total_clicks / $link_page_total);


	$referr_data = $wpdb->get_results("SELECT COUNT(click_ip) AS IPCNT,click_refer,MIN(click_date) AS min_date, MAX(click_date) AS max_date,click_ip FROM ".$wpdb->prefix."tracking_clicks WHERE link_id = '".$wpdb->escape($link_id)."' GROUP BY click_ip ORDER BY IPCNT DESC LIMIT $limitvalue,$link_page_total");
	$count = count($referr_data);

	$page_links = paginate_links( array(
		'base' => add_query_arg( 'paged', '%#%#in_clicks' ),
		'format' => '',
		'prev_text' => __('&laquo;'),
		'next_text' => __('&raquo;'),
		'total' => $numofpages,
		'current' => $paged
	));

	if ( $page_links ) { 
		$page_links_text = sprintf( '<span class="displaying-num">' . __( 'Displaying %s&#8211;%s of %s' ) . '</span>%s',
		number_format_i18n( ( $paged - 1 ) * $link_page_total + 1 ),
		number_format_i18n( min( $paged * $link_page_total, $total_clicks ) ),
		number_format_i18n( $total_clicks ),
		$page_links
	); 

		echo "<div class='tablenav'><div class='tablenav-pages'>$page_links_text</div></div>";
	}
	echo '</td></tr></table>';
	?>
	<table class="widefat comments-box " cellspacing="0">
	<thead>
		<tr>
		<th>Clicks</th>
		<th>IP Address</th>
		<th>First Click</th>
		<th>Last Click</th>
		<th>Referrer</th>
		<?
		if($count >= '1'){
			for($i=0;$i<$count;$i++){
		?>
		  </tr>
			<tr>
			<td><?=$referr_data[$i]->IPCNT;?></td>
			<td><a href="<?php echo $page_url.'&ip='.ip2long($referr_data[$i]->click_ip); ?>"><?=$referr_data[$i]->click_ip;?></a></td>
			<td><?=mysql2date(get_option('date_format').' '.get_option('time_format'),$referr_data[$i]->min_date);?></td>
			<td><?=mysql2date(get_option('date_format').' '.get_option('time_format'),$referr_data[$i]->max_date);?></td>
			<td><?php if($referr_data[$i]->click_refer == ''){ echo 'N/A'; } else { ?> <a href="<?php echo $referr_data[$i]->click_refer;?>" target="_blank" title=""><?=(strlen($referr_data[$i]->click_refer) >= 70 ? substr($referr_data[$i]->click_refer,0,70).'...' : $referr_data[$i]->click_refer);?></a><? } ?></td>
			
		<?
			}
		} else {
			echo '</tr><tr><td colspan="5">No Clicks Found</td></tr>';
		}
		?>
		<tbody id="the-comment-list" class="list:comment">
		</tbody>
		</table>
	<?

	if ( $page_links ) { 
		$page_links_text = sprintf( '<span class="displaying-num">' . __( 'Displaying %s&#8211;%s of %s' ) . '</span>%s',
		number_format_i18n( ( $paged - 1 ) * $link_page_total + 1 ),
		number_format_i18n( min( $paged * $link_page_total, $total_clicks ) ),
		number_format_i18n( $total_clicks ),
		$page_links
	); 

		echo "<div class='tablenav'><div class='tablenav-pages'>$page_links_text</div></div>";
	}

	$sql = "SELECT weekday(click_date) AS Day,COUNT(weekday(click_date)) AS CLICKCOUNT FROM `wp_tracking_clicks` WHERE link_id = '".$wpdb->escape($link_id)."' GROUP BY Day ORDER BY Day";
	$result = $wpdb->get_results($sql);
	$total_days = count($result);
	//unset($result);

	echo '<h3>Clicks by Day</h3>';

	?>
	<table class="widefat comments-box " cellspacing="0">
	<thead>
		<tr>
			<th>Monday</th>
			<th>Tuesday</th>
			<th>Wednesday</th>
			<th>Thursay</th>
			<th>Friday</th>
			<th>Saturday</th>
			<th>Sunday</th>
		</tr>
	</thead>
		<tr>
		<?php
		$day_results = array();
		for($i=0;$i<7;$i++){
			if(isset($result[$i]->Day)){
				$day_results[$result[$i]->Day] = $result[$i]->CLICKCOUNT;
			}
		}
		for($i=0;$i<7;$i++){
			if(!array_key_exists($i,$day_results)){
				$day_results[$i] = 0;
			}
			echo '<td>'.number_format_i18n($day_results[$i]).'</td>';
		 } ?>
		</tr>
	<tbody id="the-comment-list" class="list:comment">
	</tbody>
	</table>

	<?

	$sql = "SELECT HOUR(click_date) AS Hour,COUNT(HOUR(click_date)) AS Clicks FROM `wp_tracking_clicks` WHERE link_id = '".$wpdb->escape($link_id)."' GROUP BY Hour ORDER BY Hour";
	$result = $wpdb->get_results($sql);
	$total_hours = count($result);
	//unset($result);

	echo '<h3>Clicks by Hour</h3>';

	?>
	<table class="widefat comments-box " cellspacing="0">
	<thead>
		<tr>
		<?
			$append = 'AM';
			for($i=0;$i<12;$i++){
				$hour = ($i == '0' ? '12' : $i);
				echo "<th>$hour $append</th>";
			}
		?>
		</tr>
		<tr>
		<?
			for($i=0;$i<12;$i++){
				//check for hour ending
				$Clicks = 0;
				foreach($result AS $key => $value){
					if($i > 12){
						break;
					}

					if($value->Hour == $i){ 
						$Clicks = $value->Clicks;
					}
				}
		?>
			<td><?=number_format_i18n($Clicks);?></td>
			
		<?
			}
		?>
		</tr>

		<tbody id="the-comment-list" class="list:comment">
		</tbody>
		</table>

		<br \>


	<table class="widefat comments-box " cellspacing="0">
	<thead>
		<tr>
		<?
			$append = 'PM';
			for($i=0;$i<12;$i++){
				$hour = ($i == '0' ? '12' : $i);
				echo "<th>$hour $append</th>";
			}
		?>
		</tr>
		<tr>
		<?
			for($i=0;$i<12;$i++){
				//check for hour ending
				$Clicks = 0;
				foreach($result AS $key => $value){

					if($value->Hour == $i+12){ 
						$Clicks = $value->Clicks;
					}
				}
		?>
			<td><?=number_format_i18n($Clicks);?></td>
			
		<?
			}
		?>
		</tr>

		<tbody id="the-comment-list" class="list:comment">
		</tbody>
		</table>

		<table width="100%" align="center">
		<tr>
			<td align="center"><? wp_click_track_display_pie_hour_chart($result); ?></td>
			<td align="center"><? wp_click_track_display_pie_day_chart($day_results); ?></td>
		</td>
		</table>

	<?
}


function wp_click_track_admin_list_links($req, $page, $paged, $ref_paged){
	global $wpdb;

	$sql = "SELECT COUNT(link_id) AS LINKCNT FROM ".$wpdb->prefix."tracking_links ";
	$result = $wpdb->get_results($sql);
	$result = $result['0'];
	$total_links = $result->LINKCNT;

	$plugin_options = get_option('click_tracker');
	$link_page_total = $plugin_options['link_list_count'];

	$limitvalue = $paged * $link_page_total - ($link_page_total);

	$numofpages = ceil($total_links / $link_page_total);

	$result = wp_click_track_get_link_data(" ORDER BY link_total_clicks DESC LIMIT $limitvalue,$link_page_total");
	$select_total = count($result);
	if($select_total >= '1'){

		echo '<table width="100%"><tr><td>';
		
		echo '<h3>Click Tracked Links</h3>';
		
		echo '</td><td align="right">';

		$page_links = paginate_links( array(
			'base' => add_query_arg( 'paged', '%#%' ),
			'format' => '',
			'prev_text' => __('&laquo;'),
			'next_text' => __('&raquo;'),
			'total' => $numofpages,
			'current' => $paged
		));

		if ( $page_links ) {
			$page_links_text = sprintf( '<span class="displaying-num">' . __( 'Displaying %s&#8211;%s of %s' ) . '</span>%s',
			number_format_i18n( ( $paged - 1 ) * $link_page_total + 1 ),
			number_format_i18n( min( $paged * $link_page_total, $total_links ) ),
			number_format_i18n( $total_links ),
			$page_links
		); 

			echo "<div class='tablenav'><div class='tablenav-pages'>$page_links_text</div></div>";
		}
		echo '</td></tr></table>';

		wp_click_track_list_links($result, $select_total,FALSE,FALSE);

		 if ( $page_links ) {
			$page_links_text = sprintf( '<span class="displaying-num">' . __( 'Displaying %s&#8211;%s of %s' ) . '</span>%s',
			number_format_i18n( ( $paged - 1 ) * $link_page_total + 1 ),
			number_format_i18n( min( $paged * $link_page_total, $total_links ) ),
			number_format_i18n( $total_links ),
			$page_links
		); 

			echo "<div class='tablenav'><div class='tablenav-pages'>$page_links_text</div></div>";
		}

	} else {

		echo 'No Links Found';
		
	}

	?>
	</form>
	</div>

	<?

	$date = date("Y-m-d",mktime(0, 0, 0, date("m")  , date("d")-30, date("Y")));
	$sql = "SELECT COUNT(tc.link_id) AS click_count, date_format(click_date,\"%Y-%m-%d\") AS click_date_f FROM wp_tracking_clicks tc, wp_tracking_links tl WHERE tc.link_id = tl.link_id AND date_format(click_date,\"%Y-%m-%d\") >= '$date' GROUP BY click_date_f ORDER BY click_date ";

	$result = $wpdb->get_results($sql);
	$total = count($result);
	$dates = array();
	$clicks = array();
	for($i=0;$i<$total;$i++){
		$dates[$i] = "data.setCell($i, 0, '".mysql2date(get_option('date_format'),$result[$i]->click_date_f)."');";
		$clicks[$i] = "data.setCell($i, 1, ".$result[$i]->click_count.");";
	}

	?>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["linechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
	  var data = new google.visualization.DataTable();
	  data.addColumn('string', 'Date');
	  data.addColumn('number', 'Clicks');
	  data.addRows(<?php echo $total; ?>);
	  <?php echo implode("\n",$dates); ?>
	  <?php echo implode("\n",$clicks); ?>


        var chart = new google.visualization.LineChart(document.getElementById('click_chart_div'));
        chart.draw(data, {width: 950, height: 300, legend: 'bottom', title: 'Click Tracks by Date'});
      }
    </script>

	<div id='click_chart_div' style='width: 650px; height: 240px;' align="center"></div>

	<div style="height:100px"></div>
	<?
}

// Create the function to output the contents of our Dashboard Widget

function wp_click_track_admin_dashboard_widget() {
	// Display whatever it is you want to show
	global $wpdb;

	$date = date("Y-m-d",mktime(0, 0, 0, date("m")  , date("d")-14, date("Y")));
	$sql = "SELECT COUNT(tc.link_id) AS click_count, date_format(click_date,\"%Y-%m-%d\") AS click_date_f FROM wp_tracking_clicks tc, wp_tracking_links tl WHERE tc.link_id = tl.link_id AND date_format(click_date,\"%Y-%m-%d\") >= '$date' GROUP BY click_date_f ORDER BY click_date ";

	$result = $wpdb->get_results($sql);
	$total = count($result);
	$dates = array();
	$clicks = array();
	for($i=0;$i<$total;$i++){
		$dates[$i] = "data.setCell($i, 0, '".mysql2date(get_option('date_format'),$result[$i]->click_date_f)."');";
		$clicks[$i] = "data.setCell($i, 1, ".$result[$i]->click_count.");";
	}

	?>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["linechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
	  var data = new google.visualization.DataTable();
	  data.addColumn('string', 'Date');
	  data.addColumn('number', 'Clicks');
	  data.addRows(<?php echo $total; ?>);
	  <?php echo implode("\n",$dates); ?>
	  <?php echo implode("\n",$clicks); ?>


        var chart = new google.visualization.LineChart(document.getElementById('click_chart_div'));
        chart.draw(data, {width: 500, height: 240, legend: 'bottom', title: 'Click Tracks by Date'});
      }
    </script>

	<div id='click_chart_div' style='width: 650px; height: 240px;'></div>

	<div id="stats-info">
	<br />

	<table width="100%" border="0" cellspacing="0" cellpadding="0">
	  <tr>
		<td width="50%" valign="top"><h4 class="heading">Top Links</h4>
		<?php
		$date = date("Y-m-d");
		$top_links = wp_click_track_get_link_data(" ORDER BY link_total_clicks DESC, link_unique_clicks DESC LIMIT 8 ");
		//print_r($top_links);
		$total = count($top_links);
		$site_url = get_option( 'siteurl' );
		for($i=0;$i<$total;$i++){
			echo '<a href="'.$site_url.'/wp-admin/plugins.php?page=wp-click-track/click-tracker.php&link='.$top_links[$i]->link_id.'" title="'.$top_links[$i]->link_title.'">'.$top_links[$i]->link_title.'</a><br />';
			echo 'Total: '.$top_links[$i]->link_total_clicks.' Unique: '.$top_links[$i]->link_unique_clicks.'<br>';
		}
		?>
		</td>
		<td width="50%" valign="top"><h4 class="heading">Todays Clicks</h4>
		<?php
		$sql = "SELECT COUNT(click_id) AS click_count,wp_tracking_clicks.link_id AS link_id, date_format(click_date,\"%Y-%m-%d\") AS click_date, link_title, link_destination, click_refer FROM wp_tracking_links,wp_tracking_clicks WHERE wp_tracking_links.link_id = wp_tracking_clicks.link_id AND date_format(click_date,\"%Y-%m-%d\") = '$date' AND click_refer != '' GROUP BY wp_tracking_clicks.link_id ORDER BY click_count LIMIT 8";

		$result = $wpdb->get_results($sql);
		$total = count($result);
		if($total == '0'){
			echo 'No Clicks Today';
		} else {

			for($i=0;$i<$total;$i++){
				echo '<a href="'.$site_url.'/wp-admin/plugins.php?page=wp-click-track/click-tracker.php&link='.$result[$i]->link_id.'" title="'.$result[$i]->link_title.'">'.$result[$i]->link_title.'</a><br />';
				echo 'Total: '.$result[$i]->click_count.'<br>';
			}
		}
		?>
		</td>
	  </tr>
	</table>

	<div align="right">
	<a class="button" href="<?php echo $site_url;?>/wp-admin/plugins.php?page=wp-click-track/click-tracker.php">View All</a>
	</div>
	</div>

	<?
	//$clicks = wp_click_track_get_clicks(" tc, ".$wpdb->prefix."tracking_links tl WHERE tl.link_id = tc.link_id AND click_date " 
}

function wp_click_track_admin_add_dashboard_widgets() {
	wp_add_dashboard_widget('wp_click_track_admin_dashboard_widget', 'Click Tracker', 'wp_click_track_admin_dashboard_widget');	
}